
import cv2 
from PIL import Image
import pathlib
import os , sys
import time
import dlib
# 大一寸证件照390*567 一寸证件照295px*413px
# width= 295 #宽   
# hight= 413 #高
width= 390 #宽
hight= 567 #高
p=0.2 #上下比例
w=0.3 #扩展比例
root=pathlib.Path(os.path.dirname(os.path.realpath(sys.argv[0])))
detector = dlib.get_frontal_face_detector()
def eachFile(filepath):
    filepath=os.path.join('%s\%s' % (filepath, "source"))
    pathDir =  os.listdir(filepath)
    for allDir in pathDir:
        child = os.path.join('%s\%s' % (filepath, allDir))
        findface(child)

def findface(file):
    global path
    img=cv2.imread(file)
    simg=cv2.imread(file)
    gray_frame = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces=detector(gray_frame, 1)
    
    print("发现{0}个人脸!".format(len(faces)))
    print(file)
    faces=show_detection(img, faces)

    show(simg)
    #print(faces[0])
    #print(faces[0][0])
    if(len(faces)==0):
        cv2.imwrite(os.path.join(path,"failed",os.path.split(os.path.realpath(file))[1]),img)
    elif (len(faces)==1):
        filename=os.path.join(path,"successful",os.path.split(os.path.realpath(file))[1])
        #filename="d:/python/successful/"+os.path.split(os.path.realpath(file))[1]
        
        save(simg,filename,faces[0][0],faces[0][1],faces[0][2],faces[0][3])
    elif (len(faces)>1):
        i=0
        for(x1,y1,x2,y2) in faces:
            '''
            p=0.3
            ww=int(w*0.2)
            y1=int(((w+ww*2)/0.6875)*p)
            y2=int(((w+ww*2)/0.6875)*(1-p))
            crop_img = img[y-y1:y+y2,x-ww:x+w+ww] 
            res = cv2.resize(crop_img,(390, 567), interpolation = cv2.INTER_CUBIC)
            filename="d:/python/successful/"+os.path.split(os.path.realpath(file))[1]+str(i)+".jpg"
            cv2.imwrite(filename,res)
            Image.open(filename).save(filename,None,dpi=(300.0,300.0))
            cv2.rectangle(img,(x,y),(x+w,y+w),(0,255,0),3)
            cv2.imshow("image", res)
            '''
            filename=os.path.join(path,"repeat",os.path.split(os.path.realpath(file))[1]+str(i)+".jpg")
            #filename="d:/python/repeat/"+os.path.split(os.path.realpath(file))[1]+str(i)+".jpg"
            
            save(simg,filename,x1,y1,x2,y2)
            i+=1
        cv2.imwrite(os.path.join(path,"repeat",os.path.split(os.path.realpath(file))[1]),simg)
     
    

def show_detection(image, faces):
    img=image
    f=[]
    if(len(faces)!=0):
        for (i,face) in enumerate(faces):
            cv2.rectangle(img, (face.left(), face.top()), (face.right(), face.bottom()), (0, 128, 0), 1)
            x=int((face.right()-face.left())*w)
            y2= int((face.bottom()-face.top())*w)
            y1=int(x+face.bottom()-(hight*(face.right()-face.left()+2*x)/width))
            x1=face.left()-x
            x2=face.right()+x
            ht=(hight*(face.right()-face.left()+x+x))/width
            y1=int(face.bottom()+ht*p)
            y2=int(y1-ht)
            cv2.rectangle(img, (x1, y1), (x2,y2), (0, 0, 255), 1)
            f.append((x1,y1,x2,y2))
        return f
    else:
        return None

def show(img):
    max=800
    print(img.shape)
    hight=img.shape[0]
    wight=img.shape[1]
    if(hight>wight):
        p=float(wight/hight)
        hight=max
        wight=int(hight*p)
    else:
        p=float(hight/wight)
        wight=max
        hight=int(wight*p)
    res = cv2.resize(img,(wight,hight), interpolation = cv2.INTER_CUBIC)
    cv2.namedWindow("enhanced",0)
    cv2.resizeWindow("enhanced", wight,hight)
    cv2.imshow("enhanced", img) 
    time.sleep(0.3)



def save(img,filepath,x1,y1,x2,y2):
    crop_img = img[y2:y1,x1:x2] 
    print(f"size:{x2-x1},{y1-y2}")
    try:
        res = cv2.resize(crop_img,(width, hight), interpolation = cv2.INTER_CUBIC)
        cv2.imshow("image", crop_img)
        cv2.imwrite(filepath,res)
        Image.open(filepath).save(filepath,None,dpi=(300.0,300.0))
        
    except :
        res = None
        pass

def mkdir(path):
    # 引入模块
    import os
    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则不创建，并提示目录已存在
        print(path + ' 目录已存在')
        return False

if __name__ =="__main__":
    global path
    path=os.path.split(os.path.realpath(__file__))[0]
    print(path)
    mkdir(path+"/source")
    mkdir(path+"/repeat")
    mkdir(path+"/successful")
    mkdir(path+"/failed")
    #print(os.path.split(os.path.realpath(__file__))[1])

    eachFile(os.path.split(os.path.realpath(__file__))[0])
    #input("enter:")
